package com.hw.core.system.controller;

import com.hw.core.system.entity.User;
import com.hw.core.system.service.GroupService;
import com.hw.core.system.service.RoleService;
import com.hw.core.system.service.UserService;
import com.hw.core.util.PasswordUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger( UserController.class );
    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;


    @Autowired
    private RoleService roleService;


    @GetMapping("list")
    @RequiresPermissions(value = "用户查询")
    public String list(Model model) {
        model.addAttribute( "users", userService.list() );
        return "user/listUser";
    }

    @GetMapping("edit")
    @RequiresPermissions(value = "用户修改")
    public String edit(Integer id, Model model) {
        model.addAttribute( "user", userService.getUserById( id ) );
        model.addAttribute( "groups", groupService.findAll() );
        model.addAttribute( "roles", roleService.findAll() );
        return "user/editUser";
    }

    @PostMapping("edit")
    @RequiresPermissions(value = "用户修改")
    @ResponseBody
    public String edit(User user) {

        userService.update( user );
        return "修改成功";
    }


    @GetMapping("add")
    @RequiresPermissions(value = "用户新增")
    public String add(Model model) {
        model.addAttribute( "groups", groupService.findAll() );
        model.addAttribute( "roles", roleService.findAll() );
        return "user/addUser";
    }

    @PostMapping("add")
    @RequiresPermissions(value = "用户新增")
    @ResponseBody
    public String save(User user) {
        user.setCreateTime( new Date() );
        user.setImg( "/img/tx/touxiang0.jpg" );
        user.setPassword( PasswordUtil.getPasswordByUsernameAndPassword( user.getName(), user.getPassword() ) );
        userService.save( user );

        return "保存成功";
    }

    @PostMapping("resetPwd")
    @RequiresPermissions(value = "重置密码")
    @ResponseBody
    public String resetPwd(Integer id) {
        userService.resetPwd( id );
        return "密码已经重置为123，请尽快修改密码";

    }


    @PostMapping("delete")
    @RequiresPermissions(value = "用户删除")
    @ResponseBody
    public String delete(Integer id) {
        userService.delete( id );
        return "删除成功";

    }


}
